// pages/result/result.js
const QRCode = require('../../utils/qrcode.js')
import rpx2px from '../../utils/rpx2px.js'
const moment = require('../../utils/moment.js')
const networkManager = require('../../utils/networkManager.js')
import Dialog from '../../component/dialog/dialog';

let qrcode;

// 300rpx 在6s上为 150px
const qrcodeWidth = rpx2px(300)

Page({

  /**
   * 页面的初始数据
   */
  data: {
    text: 'https://github.com/tomfriwel/weapp-qrcode',
    image: '',
    // 用于设置wxml里canvas的width和height样式
    qrcodeWidth: qrcodeWidth,
    qrCodeTickets: [],
    orderId: '',
    title: '',
    info: {},
    payParams: {},
    ticketTypes: {
      '4': '会员票',
      '0': '早鸟票',
      '1': '预售票',
      '2': '现场票',
      '3': 'VIP票'
    },
    isPaied: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const orderId = decodeURIComponent(options.orderId)
    const title = decodeURIComponent(options.title)

    const payParams = JSON.parse(wx.getStorageSync(orderId) || '{}')

    this.setData({ orderId, title, payParams })

    const { token } = wx.getStorageSync('userInfo')
    networkManager._get(`/ticket/orderDetail?token=${token}&orderId=${orderId}`, (res) => {
      if (res && res.code === 0) {
        res.data.orderCreateTime = moment(res.data.orderCreateTime).format('YYYY-MM-DD hh:mm')
        const codes = res.data.codes

        this.setData({ info: res.data, codes, isPaied: res.data.hasPay === 1 })
        if (res.data.hasPay === 1) {
          
          codes.forEach((item, index) => this.renderQrcode(item.code, index))
        }
      } else {
        wx.showToast({
          icon: 'none',
          title: '网络错误，请稍后重试',
        })
      }
    }, console.error)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    // const { token } = wx.getStorageSync('userInfo')
    // const {orderId, isPaied} = this.data

    // networkManager._post_json('/ticket/order/delete', { token, orderId }, (res) => {

    // }, console.error)
    // if (!isPaied) {
    //   Dialog.confirm({
    //     message: '离开此页面，将会删除订单。确认离开？'
    //   }).then(() => {

    //     networkManager._post_json('/ticket/order/delete', { token, orderId }, (res) => {

    //     }, console.error)
    //   }).catch(console.error)
    // }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    // const { token } = wx.getStorageSync('userInfo')
    // const { orderId } = this.data
    // networkManager._post_json('/ticket/order/delete', { token, orderId }, (res) => {

    // }, console.error)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  renderQrcode : function(txt, index) {
    const z = this
    qrcode = new QRCode('canvas' + index, {
      usingIn: this, // usingIn 如果放到组件里使用需要加这个参数
      // text: "https://github.com/tomfriwel/weapp-qrcode",
      // image: '/images/bg.jpg',
      width: qrcodeWidth,
      height: qrcodeWidth,
      colorDark: "#000",
      colorLight: "#fff",
      correctLevel: QRCode.CorrectLevel.H,
    });

    // 生成图片，绘制完成后调用回调
    qrcode.makeCode(txt, () => {
      // 回调
      qrcode.exportImage(function (path) {
        console.log(path)
        const codes = z.data.codes
        codes[index].imgSrc = path
        z.setData({codes})
      })
    })
  },

  submit: function() {
    const {orderId, payParams} = this.data
    const { token } = wx.getStorageSync('userInfo')

    const { appId, nonceStr, timeStamp, package: packageStr, paySign, signType } = payParams

    wx.requestPayment({
      timeStamp,
      nonceStr,
      signType,
      paySign,
      package: packageStr,
      success: (res) => {
        if (res.errMsg === 'requestPayment:ok') {
          this.setData({ isPaied: true })


          networkManager._get(`/ticket/orderDetail?token=${token}&orderId=${orderId}`, (res) => {
            if (res && res.code === 0) {
              wx.removeStorageSync(orderId)

              res.data.orderCreateTime = moment(res.data.orderCreateTime).format('YYYY-MM-DD hh:mm')
              const codes = res.data.codes

              this.setData({ info: res.data, codes, isPaied: res.data.hasPay === 1 })

              codes.forEach((item, index) => {
                this.renderQrcode(item.code, index)
              })

            } else {
              wx.showToast({
                icon: 'none',
                title: '网络错误，请稍后重试',
              })
            }
          }, console.error)
        }
      },
      fail: (res) => {
        wx.showToast({
          icon: 'none',
          title: '支付失败，请稍后重试',
        })
      }
    })
    
  }
})